﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using eTerm.NetSocket.Utils;
using System.Text.RegularExpressions;
using eTerm.NetSocket.Net;
namespace eTerm.NetSocket
{
    public class WapFetion
    {
        private string server = "http://f.10086.cn";
        private string mobile;
        private string password;
        private CookieContainer cookies = new CookieContainer();

        public event EventHandler OnLogIn;

        public event EventHandler OnFailed;

        public event EventHandler OnSent;

        private delegate string ExecuteLogInCallback();
        private delegate bool ExecuteSendCallback(string mobile, string message);

        /// <summary>
        /// 异步登录
        /// </summary>
        public void LogInAsync() {
            ExecuteLogInCallback ec = new ExecuteLogInCallback(Login);
            ec.BeginInvoke(new AsyncCallback(l => {
                ExecuteLogInCallback ef = l.AsyncState as ExecuteLogInCallback;
                string result = ef.EndInvoke(l);
                if (result.Contains(@"您正在登录中国移动WAP飞信") && OnLogIn != null)
                    OnLogIn(this, EventArgs.Empty);
                else if(OnFailed != null)
                    OnFailed(this, EventArgs.Empty);
                l.AsyncWaitHandle.Close();
            }), ec);
        }

        /// <summary>
        /// 异步发送短信
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="message"></param>
        public void SendAsync(string mobile, string message) {
            ExecuteSendCallback ec = new ExecuteSendCallback(Send);
            ec.BeginInvoke(mobile,message, new AsyncCallback(l =>
            {
                ExecuteSendCallback ef = l.AsyncState as ExecuteSendCallback;
                bool result = ef.EndInvoke(l);
                if (result && OnSent != null)
                    OnSent(this, EventArgs.Empty);
                else if (OnFailed != null)
                    OnFailed(this, EventArgs.Empty);
                l.AsyncWaitHandle.Close();
            }), ec);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <param name="password">密码</param>
        public WapFetion(string mobile, string password)
        {
            this.mobile = mobile;
            this.password = password.ToUrlEncode();
        }


        protected string PostWithCookie(string uri, string data)
        {
            using (HttpWebClient hwc = new HttpWebClient(cookies))
            {
                hwc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                return Encoding.UTF8.GetString(hwc.UploadData(uri, Encoding.UTF8.GetBytes(data)));
            }
        }

        /// <summary>
        /// 服务器地址，默认为：http://f.10086.cn
        /// </summary>
        public string FetionServerUrl { set { server = value; } }

        protected string GetUid(string mobile)
        {
            string uri = server + "/im/index/searchOtherInfoList.action";
            string data = "searchText=" + mobile;

            string result = PostWithCookie(uri, data);
            Match mc = Regex.Match(result, @"toinputMsg\.action\?touserid=(\d+)");
            if (mc.Success)
            {
                return mc.Result("$1");
            }
            return null;
        }

        protected bool ToUid(string uid, string message)
        {
            string uri = server + "/im/chat/sendMsg.action?touserid=" + uid;
            string data = "msg=" + message.ToUrlEncode();
            string result = PostWithCookie(uri, data);
            return result != null && result.Contains("发送消息成功!");
        }

        protected bool ToMyself(string message)
        {
            string uri = server + "/im/user/sendMsgToMyselfs.action";
            string data = "msg=" + message.ToUrlEncode();
            string result = PostWithCookie(uri, data);
            return result != null && result.Contains("短信发送成功!");
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <returns></returns>
        public string Login()
        {
            string uri = server + "/im/login/inputpasssubmit1.action";
            return PostWithCookie(uri, string.Format("m={0}&pass={1}&loginstatus=1", mobile, password));
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public string Logout()
        {
            string uri = server + "/im/index/logoutsubmit.action";
            return PostWithCookie(uri, "");
        }

        /// <summary>
        /// 通过手机号，给自己会好友发送消息
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public bool Send(string mobile, string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return false;
            }

            if (mobile == this.mobile)
            {
                return ToMyself(message);
            }
            else
            {
                string uid = GetUid(mobile);
                if (uid == null)
                {
                    return false;
                }
                return ToUid(uid, message);
            }
        }
    }
}
